package com.yingside.gui;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class TestComboBoxStudentFrame extends JFrame {

    private JComboBox<Student> comboBox;

    public TestComboBoxStudentFrame() {
        this.setTitle("下拉菜单窗口");
        this.setBounds(300, 300, 400, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Student s1 = new Student(1,"小刘","213123211");
        Student s2 = new Student(2,"小张","213123212");
        Student s3 = new Student(3,"小关","213123213");
        Student s4 = new Student(4,"小曹","213123214");


        comboBox = new JComboBox<>();
        comboBox.addItem(s1);
        comboBox.addItem(s2);
        comboBox.addItem(s3);
        comboBox.addItem(s4);

        this.add(comboBox);

        String str = "aaa";

        //由于，我们现在使用的是JDK1.8以上的版本，我们可以直接在内部内中使用局部变量
        //但是注意：这其实是jdk1.8以上已经自动帮我们做了转换，
        // 因为在内部内中使用的 局部变量 只能是 final修饰的常量
        //所以在JDK1.8以下的版本，如果在内部内中使用局部变量是会直接报错的
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("str = " + str);
                //str = "bbb"; 这里不能修改，str是一个常量
            }
        });



        comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){

                    //需要自己做强制转换
                    //Student selectedItem = (Student) comboBox.getSelectedItem();

                    //直接获取学生对象
                    Student student = comboBox.getItemAt(comboBox.getSelectedIndex());
                    System.out.println(student.getId() + " " + student.getName());
                }
            }
        });

        pack();

    }

    public static void main(String[] args) {
        TestComboBoxStudentFrame comboBoxFrame = new TestComboBoxStudentFrame();
        comboBoxFrame.setVisible(true);
    }
}
